﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntryEngine.Network;
using EntryEngine;
using EntryEngineServer;
using Server.Impl;
using System.Net;

namespace Server
{
    public class Plugin : IPlugin
    {
        Dictionary<string, object> old = new Dictionary<string, object>();
        COROUTINE update;
        object IPlugin.Inject(params object[] param)
        {
            Dictionary<string, object> old = (Dictionary<string, object>)param[1];

            ImplBase._DB = (_DB)param[0];
            update = EntryService.Instance.SetCoroutine(_AUTO.Update());

            this.old = new Dictionary<string, object>();
            if (old != null)
            {
                foreach (var item in old)
                    this.old[item.Key] = item.Value;

                if (old.TryGetValue("LocalDir", out object dir))
                    SetResourceDir((string)dir, (string)old["AccessUrl"]);

                if (old.TryGetValue("WX_PAY_CALLBACK", out object dir2))
                    SetWX((string)dir2, (string)old["WX_RETURN_URL"]);
            }
            this.old["Stubs"] = GetStubs;

            return this.old;
        }
        void IDisposable.Dispose()
        {
            update.Dispose();
        }

        public static
            StubHttp[]
            GetStubs(Func<HttpListenerContext> getContext)
        {
            var _service = new ImplIService();
            var _iservice = new IServiceStub(_service);

            var _user = new ImplIUser();
            var _iuser = new IUserStub(_user);
            _iuser.__GetAgent = () =>
            {
                _user.CheckToken(getContext().Request.Headers["Authorization"]);
                return null;
            };

            var _center = new ImplICenter();
            var _icenter = new ICenterStub(_center);
            _icenter.__GetAgent = () =>
            {
                _center.CheckToken(getContext().Request.Headers["Authorization"]);
                return null;
            };

            StubHttp[]
                stubs =
                {
                    _iservice,
                    _iuser,
                    _icenter,
                };
            return stubs;
        }

        public void Select(string sql)
        {
            _LOG.Info("查询SQL: {0}", sql);
            ImplBase._DB._DAO.ExecuteReader(reader =>
            {
                StringBuilder builder = new StringBuilder();
                int field = reader.FieldCount;
                while (reader.Read())
                {
                    for (int i = 0; i < field; i++)
                    {
                        builder.Append(reader[i]);
                        builder.Append('\t');
                    }
                    builder.AppendLine();
                }
                _LOG.Info(builder.ToString());
            }, sql);
        }
        public void Update(string sql)
        {
            _LOG.Info("更新SQL: {0}, 结果{1}", sql, ImplBase._DB._DAO.ExecuteNonQuery(sql));
        }
        /// <summary>测试模式</summary>
        public void DebugMode()
        {
            //T_SMSCode.IsValid = false;
            _LOG.Info("开启测试模式");
        }
        /// <summary>设置上传文件的资源目录</summary>
        /// <param name="localDir">写入文件的计算机本地目录</param>
        /// <param name="accessUrl">访问上传的资源的外网地址</param>
        public void SetResourceDir(string localDir, string accessUrl)
        {
            localDir = Path.GetFullPath(localDir);
            if (!Directory.Exists(localDir))
                Directory.CreateDirectory(localDir);
            _LOG.Info("上传资源目录：{0} 资源访问URL：{1}", localDir, accessUrl);
            Environment.CurrentDirectory = localDir;
            _FILE.AccessURL = accessUrl;
            old["LocalDir"] = localDir;
            old["AccessUrl"] = accessUrl;
        }
        /// <summary>加载游戏数据表</summary>
        public void LoadTable()
        {
            // 加载数据表
            //_TABLE.Load("Tables");
            //_LOG.Info("加载数据表完成");
            //_C.Load(_IO.ReadText("Tables\\C.xml"));
            //_LOG.Info("加载共用常量表完成");
            //_CS.Load(_IO.ReadText("Tables\\CS.xml"));
            //_LOG.Info("加载服务端常量表完成");
        }
        public void AddAdmin(string name, string password)
        {
            "用户名不能为空".Check(string.IsNullOrEmpty(name));
            "密码不能为空".Check(string.IsNullOrEmpty(password));

            ImplICenter center = new ImplICenter();
            center.InitializeByAccount(name);
            "账号已存在".Check(center.User != null);

            T_CENTER_USER user = new T_CENTER_USER();
            user.Name = name;
            user.Account = name;
            user.Password = password;
            if (T_SMSCode.IsTelephone(name))
                user.Phone = long.Parse(name);

            center.Register(user, ELoginWay.其它);
            _LOG.Info("注册后台账号：{0}", name);
        }
        public void SetWX(string notifyUrl, string returnUrl)
        {
            _LOG.Info("设置微信参数：\r\n回调通知：{0}\r\n跳转页面：{1}", notifyUrl, returnUrl);
            _DB._WX.PAY_CALLBACK = notifyUrl;
            _DB._WX.RETURN_URL = returnUrl;
            old["WX_PAY_CALLBACK"] = notifyUrl;
            old["WX_RETURN_URL"] = returnUrl;
        }
        public void SetZFB(string notifyUrl, string returnUrl)
        {
            _LOG.Info("设置支付宝参数：\r\n回调通知：{0}\r\n跳转页面：{1}", notifyUrl, returnUrl);
            //_DB._ZFB.NOTIFY_URL = notifyUrl;
            //_DB._ZFB.RETURN_URL = returnUrl;
        }
    }
}
